﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;

using TIMETABLEASY;
using TIMETABLEASY.iCalManager;
using TIMETABLEASY.EasyCalendar.Model;
using TIMETABLEASY.EasyCalendar.Controler;
using TIMETABLEASY.TokenAuthentification;


namespace TIMETABLEASY
{
    /// <summary>
    /// Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {

        public string usertype;
        public int userid;
        public int usernotepadenabled;
        dbDataContext db_remote;

        public Options()
        {
            #region Initialization

            InitializeComponent();
            db_remote = new dbDataContext();

            //On récupère les attributs de l'utilisateur en cours
            SingletonTokenUser user_level = SingletonTokenUser.GetInstance();
            usertype = user_level.User_level;
            userid = user_level.User_id;
            usernotepadenabled = user_level.Notepad_enabled;

            //On coche ou non la case du notepad selon les préférences enregistrées
            if (usernotepadenabled == 0)
            {
                notepad_show_checkbox.IsChecked = false;
            }

            //On permet aux admins de modifier les parametres de connexion
            if (usertype == "administrators")
            {
                connectionFields.Visibility = Visibility.Visible;
            }

            try
            {
                getConnectionString();
            }
            catch (Exception)
            {
                MessageBox.Show("Error during the retrieving of connection info. Please contact your administrator.");
            }

            #endregion

        }

        #region fonctions options

        private void getConnectionString()
        {
            //On récupère la chaine
            ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;

            //On la stocke dans un énumérateur (cas de plusieurs chaines)
            IEnumerator connectionStringsEnum = connectionStrings.GetEnumerator();

            //On fait les opérations sur la bonne chaine
            int i = 0;

            while (connectionStringsEnum.MoveNext())
            {
                string name = connectionStrings[i].Name;

                if (name == "TIMETABLEASY.Properties.Settings.dbConnectionString")
                {
                    string connectionsettings_temp = connectionStrings[name].ToString();
                    string[] connectionsettings = connectionsettings_temp.Split(';');

                    //On découpe la chaine pour récupérer l'adresse IP
                    string connectionlocation_temp = connectionsettings[0];
                    string[] connectionlocation = connectionlocation_temp.Split('=');
                    string address_ip = connectionlocation[1];

                    database_location_textbox.Text = address_ip;

                    //On découpe la chaine pour récupérer le nom de la bdd
                    string connectionname_temp = connectionsettings[1];
                    string[] connectionname = connectionname_temp.Split('=');
                    string bdd_name = connectionname[1];

                    database_name_textbox.Text = bdd_name;

                    //On découpe la chaine pour récupérer le login de la bdd
                    string connectionlogin_temp = connectionsettings[3];
                    string[] connectionlogin = connectionlogin_temp.Split('=');
                    string login = connectionlogin[1];

                    database_login_textbox.Text = login;

                    //On découpe la chaine pour récupérer le mot de passe de la bdd
                    string connectionpassword_temp = connectionsettings[4];
                    string[] connectionpassword = connectionpassword_temp.Split('=');
                    string password = connectionpassword[1];

                    database_password_passwordbox.Password = password;

                    ///////////////////////////////////////
                    //Structure de la chaine : Data Source=0.0.0.0;Initial Catalog=timetableasy;Persist Security Info=True;User ID=timetableasy;Password=password
                    //////////////////////////////////////
                }

                i++;
            }
        }

        private void setConnectionString()
        {
            string database_location = database_location_textbox.Text;
            string database_login = database_login_textbox.Text;
            string database_password = database_password_passwordbox.Password;
            string database_name = database_name_textbox.Text;

            string connectionstring = "Data Source=" + database_location + ";Initial Catalog=" + database_name + ";Persist Security Info=True;User ID=" + database_login + ";Password=" + database_password + "";

            try
            {
                System.Windows.Forms.DialogResult dlgResult = System.Windows.Forms.MessageBox.Show("WARNING : Be sure that all filled datas are correct. If not, you won't be able to connect to the software", "Database Configuration", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question);
                if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                {
                    Configuration c = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

                    ConnectionStringsSection section = (ConnectionStringsSection)c.GetSection("connectionStrings");
                    section.ConnectionStrings["TIMETABLEASY.Properties.Settings.dbConnectionString"].ConnectionString = connectionstring;
                    c.Save();

                    MessageBox.Show("The software must be restarted");
                    restart();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Error during the configuration of database connection.");
            }

        }

        //On redémarre l'application
        private void restart()
        {

            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            Application.Current.Shutdown();
        }

        //On enregistre les préférences du notepad
        private void set_notepad_pref()
        {
            bool notepad_always_active = (bool)notepad_show_checkbox.IsChecked;

            if (notepad_always_active)
            {
                switch (usertype)
                {
                    case "administrators":

                        administrators admin1 = (from e in db_remote.administrators
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        admin1.notepad_enabled = 1;

                        db_remote.SubmitChanges();

                        break;

                    case "managers":

                        managers manager1 = (from e in db_remote.managers
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        manager1.notepad_enabled = 1;

                        db_remote.SubmitChanges();

                        break;

                    case "students":

                        students student1 = (from e in db_remote.students
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        student1.notepad_enabled = 1;

                        db_remote.SubmitChanges();

                        break;

                    case "teacher":

                        teacher teacher1 = (from e in db_remote.teacher
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        teacher1.notepad_enabled = 1;

                        db_remote.SubmitChanges();

                        break;

                    default:
                        break;

                }
            }

            else if (!notepad_always_active)
            {
                switch (usertype)
                {
                    case "administrators":

                        administrators admin1 = (from e in db_remote.administrators
                                                 where e.id == userid
                                                 select e).FirstOrDefault();

                        admin1.notepad_enabled = 0;

                        db_remote.SubmitChanges();

                        break;

                    case "managers":

                        managers manager1 = (from e in db_remote.managers
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        manager1.notepad_enabled = 0;

                        db_remote.SubmitChanges();

                        break;

                    case "students":

                        students student1 = (from e in db_remote.students
                                             where e.id == userid
                                             select e).FirstOrDefault();

                        student1.notepad_enabled = 0;

                        db_remote.SubmitChanges();

                        break;

                    case "teacher":

                        teacher teacher1 = (from e in db_remote.teacher
                                            where e.id == userid
                                            select e).FirstOrDefault();

                        teacher1.notepad_enabled = 0;

                        db_remote.SubmitChanges();

                        break;

                    default:
                        break;

                }
            }

        }


        #endregion

        #region controles options

        private void applyoptionsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (usertype == "administrators")
                {
                    setConnectionString();
                }

                set_notepad_pref();
            }
            catch (Exception)
            {
                
            }
        }


        private void canceloptionsButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #endregion


    }
}
